package com.techsoul.common.security.handler;

import com.alibaba.fastjson.JSON;
import com.techsoul.common.core.constant.ApiConstants;
import com.techsoul.common.core.enums.HttpStatusEnum;
import com.techsoul.common.core.manager.AsyncManager;
import com.techsoul.common.core.manager.factory.AsyncFactory;
import com.techsoul.common.core.pojo.Result;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.security.pojo.LoginUser;
import com.techsoul.common.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义退出处理类 返回成功
 *
 * @author liuen
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private Result result;

    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLoginLog(userName, ApiConstants.LOGOUT, "退出成功"));
        }
        ServletUtils.renderString(response, JSON.toJSONString(result.error(HttpStatusEnum.SUCCESS.getCode(), "退出成功", "")));
        // todo 单点登录-退出

    }

}
